package com.ricky.netty.demo.fileclient;

import io.netty.channel.*;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.stream.ChunkedFile;

import java.io.File;
import java.io.RandomAccessFile;

/**
 * Created by vixuan-008 on 2015/6/25.
 */
public class FileServerHandler extends SimpleChannelInboundHandler<String> {
    private static final String CR = System.getProperty("line.separator");
 
    /*
     * (non-Javadoc)
     *
     * @see
     * io.netty.channel.SimpleChannelInboundHandler#messageReceived(io.netty
     * .channel.ChannelHandlerContext, java.lang.Object)
     */
    public void messageReceived(ChannelHandlerContext ctx, String msg)
            throws Exception {

        System.out.printf("接收信息%s，然后发送文件", msg);

        Channel channel =  (SocketChannel)ctx.channel();
        File originalFile = new File("video.mkv");
        //返回文件
        channel.write(new ChunkedFile(originalFile));

        ctx.pipeline().addFirst(new ChunkedReadHandler(originalFile.length()));

        File file = new File(msg);
        if (file.exists()) {

            if (!file.isFile()) {
                ctx.writeAndFlush("Not a file : " + file + CR);
                return;
            }
            ctx.write(file + " " + file.length() + CR);
            RandomAccessFile randomAccessFile = new RandomAccessFile(msg, "r");
            FileRegion region = new DefaultFileRegion(
                    randomAccessFile.getChannel(), 0, randomAccessFile.length());
            ctx.write(region);
            ctx.writeAndFlush(CR);
            randomAccessFile.close();
        } else {
            System.out.println("没有收到文件");
            ctx.writeAndFlush("File not found: " + file + CR);
        }
    }
 
    /*
     * (non-Javadoc)
     *
     * @see
     * io.netty.channel.ChannelHandlerAdapter#exceptionCaught(io.netty.channel
     * .ChannelHandlerContext, java.lang.Throwable)
     */
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        ctx.close();
    }
}

//————————————————
//版权声明：本文为CSDN博主「在奋斗的大道」的原创文章，遵循 CC 4.0 BY-SA 版权协议，转载请附上原文出处链接及本声明。
//原文链接：https://blog.csdn.net/zhouzhiwengang/article/details/46638771